package com.example.controller;

import com.example.annotation.AccessLevel;
import com.example.dto.Response;
import com.example.dto.UserResponseDTO;
import com.example.error.ErrorCode;
import com.example.jparepository.primary.entity.CustUser;
import com.example.service.CustUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/user")
public class UserController extends AbstractController {

    @Autowired
    private CustUserService userService;

    @PostMapping("/create")
    @AccessLevel  // 需要用户登录的访问级别
    public Response<UserResponseDTO> createUser(@RequestBody CustUser user) {
        return executeAsync(() -> {
            Long requestUid = getRequestUid();
            if (requestUid == null || requestUid <= 0L) {
                return Response.failure(ErrorCode.USER_NOT_FOUND);
            }
            UserResponseDTO savedUser = userService.saveUser(user);
            return Response.success(savedUser);
        });
    }

    @GetMapping("/all")
    @AccessLevel("ADMIN")  // 需要管理员权限的访问级别
    public Response<List<UserResponseDTO>> getAllUsers(
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        return executeAsync(() -> {
            Long requestUid = getRequestUid();
            if (requestUid == null || requestUid <= 0L) {
                return Response.failure(ErrorCode.USER_NOT_FOUND);
            }
            List<UserResponseDTO> userDTOs = userService.getAllUsers(page, size);
            return Response.success(userDTOs);
        });
    }

    @GetMapping("/{uid}")
    @AccessLevel  // 需要用户登录的访问级别
    public Response<UserResponseDTO> getUserByUid(@PathVariable Integer uid) {
        return executeAsync(() -> {
            Long requestUid = getRequestUid();
            if (requestUid == null || requestUid <= 0L) {
                return Response.failure(ErrorCode.USER_NOT_FOUND);
            }
            Optional<UserResponseDTO> userDTO = userService.getUserByUid(uid);
            return userDTO.map(Response::success).orElseGet(() -> Response.failure(ErrorCode.USER_NOT_FOUND));
        });
    }
}
